package com.student_system.students.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.student_system.common.Result;
import com.student_system.students.entity.Teacher;
import com.student_system.students.service.ITeacherService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/teacher")
public class TeacherController {
    @Autowired
    private ITeacherService teacherService;

    @GetMapping("/getAll")
    public Result.ResultData<Map<String, Object>> getAllTeachers(
            @RequestParam(defaultValue = "1") int current,
            @RequestParam(defaultValue = "10") int size,
            @RequestParam(required = false) String name) {

        Page<Teacher> page = new Page<>(current, size);
        QueryWrapper<Teacher> queryWrapper = new QueryWrapper<>();
        if (StringUtils.isNotBlank(name)) {
            queryWrapper.like("name", name);
        }
        queryWrapper.orderByAsc("teacher_no");

        Page<Teacher> result = teacherService.page(page, queryWrapper);

        Map<String, Object> data = new HashMap<>();
        data.put("list", result.getRecords());
        data.put("total", result.getTotal());
        data.put("size", result.getSize());
        data.put("current", result.getCurrent());
        data.put("pages", result.getPages());

        return Result.success(data);
    }

    @GetMapping("/{teacherNo}")
    public Result.ResultData<Teacher> getTeacherById(@PathVariable Integer teacherNo) {
        Teacher teacher = teacherService.getById(teacherNo);
        if (teacher == null) {
            return Result.error("404", "教师不存在");
        }
        return Result.success(teacher);
    }

    @PostMapping("/save")
    public Result.ResultData<String> saveTeacher(@RequestBody Teacher teacher) {
        try {
            if (teacher.getTeacherNo() == null) {
                return Result.error("400", "教师编号不能为空");
            }

            if (teacherService.saveOrUpdate(teacher)) {
                return Result.success("保存成功");
            }
            return Result.error("500", "保存失败");
        } catch (Exception e) {
            return Result.error("500", "保存失败: " + e.getMessage());
        }
    }

    @DeleteMapping("/{teacherNo}")
    public Result.ResultData<Void> deleteTeacher(@PathVariable Integer teacherNo) {
        if (teacherService.removeById(teacherNo)) {
            return Result.success();
        }
        return Result.error("500", "删除失败");
    }
}